import http from '@/axios'
import {handleError} from "vue";
import {handleSuccess} from "@/api/index.js";

/**
 * 聊天相关API
 */
export const chatAPI = {
    //获取好友列表
    getFriendList: (userId) => http.get('/api/friend/list')
        .then(res => handleSuccess(res, '获取好友列表成功'))
        .catch(error => handleError(error, '获取好友列表失败')),

    // 获取好友列表并格式化
    getFormattedFriendList: async (userId) => {
        try {
            const res = await http.get('/api/friend/list', {
                params: { userId }  // 添加userId作为查询参数
            });
            const data = handleSuccess(res, '获取好友列表成功');

            // 获取所有好友的详细信息
            const friendDetails = await Promise.all(
                data.map(friend => chatAPI.getFriendInfo(friend.friendId))
            );

            // 获取所有好友的在线状态
            const onlineStatuses = await Promise.all(
                data.map(friend => chatAPI.getFriendOnlineStatus(friend.friendId))
            );

            // 合并好友列表数据和详细信息
            return data.map((friend, index) => {
                const detail = friendDetails[index];
                const status = onlineStatuses[index];
                return {
                    id: detail?.id,
                    name: friend?.nickname||detail?.username,
                    avatar: detail?.avatar || 'https://randomuser.me/api/portraits/lego/1.jpg',
                    online: status?.online === 1, // 使用API获取的在线状态
                    status: friend.status, // 好友关系状态：0-待确认, 1-已同意, 2-已拒绝, 3-已拉黑
                    lastSeen: status?.lastActive ? formatLastSeen(status.lastActive) : '未知',
                    receiverId: friend.receiverId, // 添加receiverId字段
                    relationId: friend.relationId, // 添加relationId用于处理好友请求
                    remark: friend.remark // 添加备注信息
                };
            });
        } catch (error) {
            handleError(error, '获取好友列表失败');
            return [];
        }
    },

    //获取好友信息
    getFriendInfo: async (userId) => {
        try {
            const res = await http.get('/api/user/info', {
                params: { userId }  // 添加userId作为查询参数
            });
            const data = handleSuccess(res, '获取好友信息成功');
            return {
                id: data.userId,
                name: data.username,
                avatar: data.avatar,
                email: data.email,
                phone: data.phone,
                lastSeen: formatLastSeen(data.lastActive)
            };
        } catch (error) {
            handleError(error, '获取好友信息失败');
            return null;
        }
    },

    //获取好友在线状态
    getFriendOnlineStatus: async (userId) => {
        try {
            const res = await http.get('/api/user/online', {
                params: { userId }
            });
            const data = handleSuccess(res, '获取好友在线状态成功');
            return {
                online: data.status, // 0-不在线，1-在线,2-隐身
                lastActive: data.lastActive
            };
        } catch (error) {
            handleError(error, '获取好友在线状态失败');
            return {
                online: 0, // 默认不在线
                lastActive: null
            };
        }
    },

    //添加好友
    addFriend: async (data) => {
        try {
            const res = await http.post('/api/Friend/request', data);
            return handleSuccess(res, '添加好友请求发送成功');
        } catch (error) {
            handleError(error, '好友列表中已存在该好友或等待对方确认');
            throw error;
        }
    },

    // 处理好友请求
    responseFriend: async (data) => {
        try {
            // 确保包含relationId和status
            if (!data.relationId || data.status === undefined) {
                throw new Error('缺少必要参数: relationId或status');
            }

            const res = await http.post('/api/Friend/response', {
                relationId: data.relationId,
                status: data.status
            });

            return handleSuccess(res, '处理好友请求成功');
        } catch (error) {
            if (error.response && error.response.status === 400) {
                throw new Error('请求参数不完整');
            }
            handleError(error, '处理好友请求失败');
            throw error;
        }
    },

    //删除好友
    deleteFriend: async (relationId) => {
        try {
            const res = await http.delete('/api/Friend/delete', {
                params: { relationId }
            });
            return handleSuccess(res, '删除好友成功');
        } catch (error) {
            handleError(error, '删除好友失败');
            throw error;
        }
    }
}

// 辅助函数：格式化最后活跃时间
function formatLastSeen(timestamp) {
    if (!timestamp) return '未知';

    const now = new Date();
    const lastActive = new Date(timestamp);
    const diffInHours = (now - lastActive) / (1000 * 60 * 60);

    if (diffInHours < 1) {
        return `${Math.floor(diffInHours * 60)}分钟前`;
    } else if (diffInHours < 24) {
        return `${Math.floor(diffInHours)}小时前`;
    } else {
        return `${Math.floor(diffInHours / 24)}天前`;
    }
}